package com.knife.blog.logic;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.io.VelocityWriter;

import com.knife.blog.domain.BlogInfo;
import com.knife.blog.domain.BlogNewsDoc;
import com.knife.blog.domain.BlogUser;
import com.knife.blog.domain.Photo;
import com.knife.blog.domain.PhotoDir;
import com.knife.blog.logic.impl.BlogCircleDirServiceImpl;
import com.knife.blog.logic.impl.BlogCircleDocServiceImpl;
import com.knife.blog.logic.impl.BlogCircleMemberServiceImpl;
import com.knife.blog.logic.impl.BlogCircleServiceImpl;
import com.knife.blog.logic.impl.BlogCoreServiceImpl;
import com.knife.blog.logic.impl.BlogMessageServiceImpl;
import com.knife.blog.logic.impl.BlogMusicServiceImpl;
import com.knife.blog.logic.impl.BlogPhotoDirServiceImpl;
import com.knife.blog.logic.impl.BlogResourceServiceImpl;
import com.knife.blog.logic.impl.BlogReviewServiceImpl;
import com.knife.blog.logic.impl.BlogUserServiceImpl;
import com.knife.blog.logic.impl.FriendLinkServiceImpl;
import com.knife.blog.logic.impl.PhotoServiceImpl;
import com.knife.blog.service.Config;
import com.knife.blog.util.BlogCommUtil;
import com.knife.dbo.EasyJDB;
import com.knife.util.CommUtil;
import com.knife.util.HtmlUtil;
import com.knife.web.RequestProcessor;
import com.knife.web.tools.CommTool;
import com.knife.web.tools.DbPageList;
import com.knife.web.tools.IPageList;

public class HTMLGenerater {

    private String fileName;
	private static BlogUser bloguser;
    private static String encoding = "utf-8";
    // private String baseDir="/html/";
    private static final Logger logger = (Logger) Logger.getLogger(RequestProcessor.class.getName());
    private static BlogUserService userService = BlogUserServiceImpl.getInstance();
    private static BlogDirService blogDirService = BlogCoreServiceImpl.getInstance();
    private static BlogNewsDocService blogDocService = BlogCoreServiceImpl.getInstance();
    private static PhotoService photoService = PhotoServiceImpl.getInstance();
    private static BlogReviewService reviewService = BlogReviewServiceImpl.getInstance();
    private static BlogMessageService messageService = BlogMessageServiceImpl.getInstance();
    private static BlogCircleDirService circleDirService = BlogCircleDirServiceImpl.getInstance();
    private static BlogCircleService circleService = BlogCircleServiceImpl.getInstance();
    private static BlogCircleDocService circleDocService = BlogCircleDocServiceImpl.getInstance();
    private static BlogMusicService musicService = BlogMusicServiceImpl.getInstance();
    private static BlogCircleMemberService circleMemberService = BlogCircleMemberServiceImpl.getInstance();

    public HTMLGenerater() {
    }

    //生成用户博客
    public static void generateBlog(BlogInfo blog){
        //保存样式
        saveCSS(blog);
        //--------侧面
        /*
        saveLeftArticalClassifyToHTML(blog);//左侧文章分类
        saveLeftFrindlinkToHTML(blog);//左侧友情链接
        saveLeftMessageToHTML(blog);//左侧最新留言
        saveLeftPersonInfoToHTML(blog);//左侧个人信息
        saveLeftPhotoDirToHTML(blog);//左侧最新相册
        saveLeftPhotoToHTML(blog);//左侧最新照片
        saveLeftReviewAllToHTML(blog);//左侧最新评论全部
        saveLeftReviewArticalToHTML(blog);//左侧最新评论文章
        saveLeftReviewPhotoToHTML(blog);//左侧最新评论照片
        saveLeftMusicToHTML(blog);//左侧我的音乐
        saveMusicConfigToXMl(blog);//音乐配置文件
        saveMusicListToXMl(blog);//音乐列表
        //--------头部和尾部
        saveTopToHTML(blog);
        saveBottomToHTML(blog);
        */

        //生成用户博客首页，相册首页，每个相册的首页，留言页面，生成rss，生成侧面的所有页面
        saveToHTML(blog);//重新生成用户博客首页
        saveArticleIndexToHTML(blog);//用户文章首页
        savePhotoDirIndexToHTMLByBlog(blog);//用户相册首页
        saveAllPhotoDirToHTML(blog);//生成用户所有相册,生成单个相册页面
        saveUserCircleToHTML(blog);//生成用户圈子首页
        saveRssToHTML(blog);//生成rss
        saveMessageToHTML(blog);//留言页面
    }

    /**
     * 生成文章首页
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveIndexArticleToHTML() throws Exception {
        Context context = null;
        Template template = null;
        context = new VelocityContext();

        context.put("dirList", BlogCircleDirServiceImpl.getInstance());
        context.put("list", BlogCircleServiceImpl.getInstance());
        addCommonContext(context);
        CommTool.createUtilContext(context);
        String fileName = "article.htm";
        File file = new File(Config.getWwwpath() + "/" + fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        String templateName = "/article.htm";
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成用户文章首页
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveArticleIndexToHTML(BlogInfo obj) {
        IPageList pList;
        if (obj.isUserBlog()) {
            pList = blogDocService.queryBlogNewsDoc(obj.getUsername(), 0, -1);
        } else {
            pList = blogDocService.queryBlogNewsDoc(obj.getCid(), 0, -1);
        }
        String tName = obj.getTemplate();
        if (!CommUtil.hasLength(tName)) {
            tName = "default";
        }
        String fileName = obj.getDomain() + "/article.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;

        String templateName = "/user/article.htm";

        return saveToHtml(pList, templateName, filePath, obj);
    }

    /**
     * 生成圈子首页
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveIndexCircleToHTML() throws Exception {
        Context context = null;
        Template template = null;
        context = new VelocityContext();

        context.put("dirList", BlogCircleDirServiceImpl.getInstance());
        context.put("list", BlogCircleServiceImpl.getInstance());
        addCommonContext(context);
        CommTool.createUtilContext(context);
        String fileName = "circle.htm";
        File file = new File(Config.getWwwpath() + "/" + fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        String templateName = "/circle.htm";
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成每个圈子首页
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveCircleIndexToHTML(BlogInfo circle) {
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        List lastList = circleDocService.getTopDoc(circle, "inputtime", 0, 10).getResult();
        List hotList = circleDocService.getTopDoc(circle, "readtimes", 0, 10).getResult();
        List eliteList = circleDocService.getEliteDoc(circle, "", 1, 0, 10).getResult();
        List newMemberList = circleMemberService.queryCircleMemberByCircleCid(circle.getCid(), 0, 10).getResult();
        List memberList = circleMemberService.queryCircleMemberByCircleCid(circle.getCid(), 0, -1).getResult();
        BlogInfo blog = userService.getUserBlog(circle.getUsername());
        String tName = circle.getTemplate();
        if (!CommUtil.hasLength(tName)) {
            tName = blog.getTemplate();
        }
        String fileName = circle.getDomain() + "/index.htm";
        File file = new File(Config.getWwwpath() + "/" + fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        String templateName = "/circle/circleIndex.htm";
        context.put("lastList", lastList);
        context.put("hotList", hotList);
        context.put("eliteList", eliteList);
        context.put("newMemberList", newMemberList);
        context.put("memberList", memberList);
        context.put("templateName", tName);
        context.put("circle", circle);
        context.put("circleService", BlogCircleServiceImpl.getInstance());
        addCommonContext(context);
        CommTool.createUtilContext(context);

        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;

    }

    /**
     * 生成用户圈子
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveUserCircleToHTML(BlogInfo blog) {
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        List myCircleList = circleService.queryOnwerCircle(blog.getUsername()).getResult();
        List docList = circleDocService.queryTopDocByUser(blog.getUsername(), 0, -1).getResult();
        //.queryBlogCircle("select title,url from blogcircle order by inputtime desc",null, 0, 10);
        List circleList = circleService.queryUserCircle(blog.getUsername()).getResult();
        String fileName = blog.getDomain() + "/circle.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        String templateName = "/user/circle.htm";
        context.put("docList", docList);
        context.put("myCircleList", myCircleList);
        context.put("circleList", circleList);
        context.put("blog", blog);
        addCommonContext(context);
        CommTool.createUtilContext(context);
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成用户相册首页
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveToHTML(Photo obj) throws Exception {
        System.out.println("HTMLGenerater:" + obj.getBlogcid());
        BlogInfo blog = userService.getBlogInfo(obj.getBlogcid());
        return savePhotoToHTMLByBlog(blog);

    }

    /**
     * 生成用户相册首页，包含此用户的所有照片，不分相册
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean savePhotoToHTMLByBlog(BlogInfo obj) {
        //Photo photo = photoService.getPhoto(obj.getCid());
        //List photoList = photoService.queryPhotoByBlog(obj);
        IPageList pList;
        if (obj.isUserBlog()) {
            pList = photoService.queryPhoto(obj.getUsername(), 0, -1);
        } else {
            pList = photoService.queryCirclePhoto(obj.getCid(), 0, -1);
        }
        String tName = obj.getTemplate();
        if (!CommUtil.hasLength(tName)) {
            tName = "default";
        }
        String fileName = obj.getDomain() + "/photoAll.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;

        String templateName = "/user/photoAll.htm";

        return saveToHtml(pList, templateName, filePath, obj);
    }

    /**
     * 生成用户相册首页，包含的是相册，点相册，进的是单个相册页面
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean savePhotoDirIndexToHTMLByBlog(BlogInfo obj) {
        IPageList pList;
        if (obj.isUserBlog()) {
            pList = photoService.queryPhotoDir(obj.getUsername(), 0, -1);
        } else {
            pList = photoService.queryCirclePhoto(obj.getCid(), 0, -1);
        }
        String tName = obj.getTemplate();
        if (!CommUtil.hasLength(tName)) {
            tName = "default";
        }
        String fileName = obj.getDomain() + "/photo.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;

        String templateName = "/user/photo.htm";

        return saveToHtml(pList, templateName, filePath, obj);
    }

    /**
     * 生成用户所有的单个相册页面
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveAllPhotoDirToHTML(BlogInfo obj) {
        Collection<Object> param = new ArrayList<Object>();
        param.add(obj.getUsername());
        java.util.List photoDirList = EasyJDB.getInstance().query(PhotoDir.class, "inputuser=?", param);
        if (photoDirList != null) {
            for (int i = 0; i < photoDirList.size(); i++) {
                PhotoDir photoDir = (PhotoDir) photoDirList.get(i);
                boolean ret = savePhotoDIRToHTMLByBlog(obj, photoDir.getCid());
                if (!ret) {
                    return ret;
                }
            }
        }
        return true;
    }

    /**
     * 生成用户单个相册页面，包含此用户的此相册
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean savePhotoDIRToHTMLByBlog(BlogInfo obj, String phoDirID) {
        //Photo photo = photoService.getPhoto(obj.getCid());
        //List photoList = photoService.queryPhotoByBlog(obj);
        IPageList pList;
        if (obj.isUserBlog()) {
            pList = photoService.queryPhoto(phoDirID, obj.getUsername(), 0, -1);
        } else {
            pList = photoService.queryCirclePhoto(obj.getCid(), 0, -1);
        }
        String tName = obj.getTemplate();
        if (!CommUtil.hasLength(tName)) {
            tName = "default";
        }
        String fileName = obj.getDomain() + "/html/photo-" + phoDirID + ".htm";
        String filePath = Config.getWwwpath() + "/" + fileName;

        String templateName = "/user/photodir.htm";

        return saveToHtml(pList, templateName, filePath, obj);
    }

    /**
     * 生成网站相册首页
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveIndexPhotoToHTML() {
        Context context = null;
        Template template = null;
        context = new VelocityContext();

        context.put("dirList", BlogPhotoDirServiceImpl.getInstance());
        context.put("list", BlogPhotoDirServiceImpl.getInstance());
        addCommonContext(context);
        CommTool.createUtilContext(context);
        String fileName = "photo.htm";
        File file = new File(Config.getWwwpath() + "/" + fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        String templateName = "/index/photo.htm";
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成用户留言首页
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveMessageToHTML(BlogInfo blog) {
        DbPageList pList = (DbPageList) messageService.queryAuditedMessage(blog.getCid(), 0, -1);
        String tName = blog.getTemplate();
        if (!CommUtil.hasLength(tName)) {
            tName = "default";
        }
        String fileName = blog.getDomain() + "/message.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/message.htm";
        return saveToHtml(pList, templateName, filePath, blog);
    }

    /**
     * 生成圈子留言板
     * @param circle
     * @return
     */
    public static boolean saveCircleMessageToHTML(BlogInfo circle) {
        DbPageList pList = (DbPageList) messageService.queryAuditedMessage(circle.getUsername(), 0, -1);
        String fileName = circle.getDomain() + "/message.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;

        String templateName = "/circle/message.htm";
        return saveToHtml(pList, templateName, filePath, circle);
    }

    /**
     * 生成用户首页
     * @param blog
     * @return
     */
    public static boolean saveToHTML(BlogInfo blog) {
        if (blog.getType().equals("circleBlog")) {
            return saveCircleIndexToHTML(blog);
        }
        IPageList pList = blogDocService.queryBlogNewsDoc(blog.getUsername(),
                0, -1);
        String fileName = blog.getDomain() + "/index.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/index.htm";
        return saveToHtml(pList, templateName, filePath, blog);
    }

    /**
     * 生成所有文章
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveAllDocToHTML(BlogInfo blog) throws Exception {
        Collection<Object> param = new ArrayList<Object>();
        param.add(blog.getUsername());
        java.util.List docList = EasyJDB.getInstance().query(BlogNewsDoc.class, "inputuser=?", param);
        if (docList != null) {
            for (int i = 0; i < docList.size(); i++) {
                BlogNewsDoc doc = (BlogNewsDoc) docList.get(i);
                boolean ret = saveToHTML(doc);
                if (!ret) {
                    return ret;
                }
            }
        }
        return true;
    }

    /**
     * 生成用户所有图片
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveAllPhotoDocToHTML(BlogInfo blog) throws Exception {
        Collection<Object> param = new ArrayList<Object>();
        param.add(blog.getCid());
        java.util.List docList = null;
        if (blog.isUserBlog()) {
            docList = EasyJDB.getInstance().query(Photo.class, "blogcid=?", param);
        } else {
            docList = EasyJDB.getInstance().query(Photo.class, "circlesn=?", param);
        }
        if (docList != null) {
            for (int i = 0; i < docList.size(); i++) {
                Photo photo = (Photo) docList.get(i);
                boolean ret = savePhotoDocToHtml(photo);
                if (!ret) {
                    return ret;
                }
            }
        }
        return true;
    }

    /**
     * 生成用户发表的文章
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveToHTML(BlogNewsDoc obj){
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("obj", obj);
        BlogInfo blog = userService.getUserBlog(obj.getInputuser());
        context.put("blog", blog);
        context.put("reviewService", BlogReviewServiceImpl.getInstance());
        addCommonContext(context);
        CommTool.createUtilContext(context);
        String fileName = blog.getDomain() + obj.getUrl();
        File file = new File(Config.getWwwpath() + "/" + fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        String templateName = "/user/show.htm";
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

	//生成CSS
    public static boolean saveCSS(BlogInfo blog){
        Context context = null;
        Template template = null;
        boolean ret=false;
        try{
        String fileName = blog.getDomain()+"/css/style.css";
        String templateName = "/template/"+blog.getTemplate()+"/style.css";
            File file = new File(Config.getWwwpath() + "/" + fileName);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            template = VelocityFactory.getTemplate(templateName, "utf-8");
            mergeTemplate(template, context, file);
            ret=true;
        }catch(Exception e){
            logger.error(e);
            ret=false;
        }
        return ret;
    }

    /**
     * 生成用户左侧的文章分类
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveLeftArticalClassifyToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/left-articalClassify.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/left-articalClassify.htm";
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        addCommonContext(context);
        CommTool.createUtilContext(context);
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成用户左侧的友情链接
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveLeftFrindlinkToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/left-frindlink.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/left-frindlink.htm";
        System.out.println("生成博客:"+blog.getUsername());
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        addCommonContext(context);
        CommTool.createUtilContext(context);
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成用户左侧的最新留言
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveLeftMessageToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/left-message.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/left-message.htm";


        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        addCommonContext(context);
        CommTool.createUtilContext(context);

        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成左侧的个人信息
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveLeftPersonInfoToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/left-personInfo.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/left-personInfo.htm";
        BlogUser blogUser = userService.getBlogUser(blog.getUsername());

        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        context.put("blogUser", blogUser);
        addCommonContext(context);
        CommTool.createUtilContext(context);

        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成左侧的最新相册
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveLeftPhotoDirToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/left-photodir.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/left-photodir.htm";

        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        addCommonContext(context);
        CommTool.createUtilContext(context);

        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成左侧的最新照片
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveLeftPhotoToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/left-photo.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/left-photo.htm";

        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        addCommonContext(context);
        CommTool.createUtilContext(context);

        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成左侧的最新评论全部
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveLeftReviewAllToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/left-reviewAll.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/inc/part-reviewAll.htm";
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        addCommonContext(context);
        CommTool.createUtilContext(context);

        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成左侧的最新评论文章
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveLeftReviewArticalToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/left-reviewArtical.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/inc/part-reviewArtical.htm";

        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        addCommonContext(context);
        CommTool.createUtilContext(context);

        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成左侧的最新评论照片
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveLeftReviewPhotoToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/left-reviewPhoto.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/left-reviewPhoto.htm";

        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        addCommonContext(context);
        CommTool.createUtilContext(context);

        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成用户左侧的我的音乐
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveLeftMusicToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/left-music.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/left-music.htm";
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        CommTool.createUtilContext(context);
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成左侧的我的音乐配置文件
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveMusicConfigToXMl(BlogInfo blog) {
        String fileName = blog.getDomain() + "/music/config.xml";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/config.xml";
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成左侧的我的音乐文件列表
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveMusicListToXMl(BlogInfo blog) {
        IPageList musicList = musicService.queryBlogMusic(blog.getUsername(), "", 1, 15);
        String fileName = blog.getDomain() + "/music/playlist.xml";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/playlist.xml";
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        context.put("list", musicList.getResult());
        addCommonContext(context);
        CommTool.createUtilContext(context);
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成用户头部
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveTopToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/top.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/top.htm";

        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        addCommonContext(context);
        CommTool.createUtilContext(context);

        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成用户尾部
     * @param blog
     * @return
     * @throws Exception
     */
    public static boolean saveBottomToHTML(BlogInfo blog) {
        String fileName = blog.getDomain() + "/include/bottom.htm";
        String filePath = Config.getWwwpath() + "/" + fileName;
        String templateName = "/user/bottom.htm";

        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
        addCommonContext(context);
        CommTool.createUtilContext(context);

        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

//	-----add 2010-05-11
    /**
     * 生成用户发表的图片
     * @param blog
     * @return
     */
    public static boolean savePhotoDocToHtml(Photo obj) {
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("obj", obj);
        BlogInfo blog = userService.getUserBlog(obj.getInputuser());
        context.put("blog", blog);
        PhotoDir photodir = photoService.getPhotoDir(obj.getDirid());
        context.put("photodir", photodir);
        context.put("reviewService", BlogReviewServiceImpl.getInstance());
        CommTool.createUtilContext(context);
        String fileName = obj.getHtmlurl();
        File file = new File(Config.getWwwpath() + "/" + blog.getDomain() + fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        String templateName = "/user/showPhoto.htm";
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;
    }

    /**
     * 生成rss
     * @param blog
     * @return
     */
    public static boolean saveRssToHTML(BlogInfo blog) {
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        IPageList pList = blogDocService.queryBlogNewsDoc(blog.getUsername(),
                0, -1);
        String templateName = "/tools/rss.xml";
        String fileName = blog.getDomain() + "/rss.xml";
        String filePath = Config.getWwwpath() + "/" + fileName;
        context.put("list", pList.getResult());
        context.put("blog", blog);
        ResourceBundle bundle = ResourceBundle.getBundle("SysConfig");
        Map sysConfig = new HashMap();
        for (Enumeration keys = bundle.getKeys(); keys.hasMoreElements();) {
            String bundleKey = (String) keys.nextElement();
            String key = bundleKey.substring(bundleKey.lastIndexOf(".") + 1, bundleKey.length());
            sysConfig.put(key, bundle.getString(bundleKey));
        }
        context.put("sysConfig", sysConfig);
        String path;
        path = filePath;
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        template = VelocityFactory.getTemplate(templateName, "utf-8");
        mergeTemplate(template, context, file);
        return true;

    }

    /**
     * 生成分页静态页面的公共方法
     * @param
     * @return
     * @throws Exception
     */
    public static boolean saveToHtml(IPageList pList, String templateName, String filePath, BlogInfo blog) {
        Context context = null;
        Template template = null;
        context = new VelocityContext();
        context.put("blog", blog);
		bloguser=userService.getBlogUser(blog.getUsername());
		context.put("bloguser", bloguser);
        addCommonContext(context);
        List list;
        int pageSize;
        if (pList.getResult() == null) {
            context.put("list", null);
            String path;
            path = filePath;
            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //fileName = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
            template = VelocityFactory.getTemplate(templateName, "utf-8");
            mergeTemplate(template, context, file);
            return true;
        }
        list = pList.getResult();
        int resultNum = list.size();
        pageSize = blog.getFirtpagenum();
        if (pageSize <=0) {
            pageSize = 10;
        }
        int pages = (resultNum % pageSize == 0 ? resultNum / pageSize : resultNum / pageSize + 1);
        for (int i = 0; i < pages; i++) {
            int page = i + 1;
            int begin = i * pageSize;
            int end = (i + 1) * pageSize;
            if (end > resultNum) {
                end = resultNum;
            }
            List pageList = list.subList(begin, end);
            context.put("list", pageList);
            context.put("pages", pages);
            context.put("pageSize", pageSize);
            context.put("rows", new Integer(pList.getRowCount()));
            context.put("page", page);
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1, filePath.length()).split("\\.")[0];
            fileName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            //filePath=filePath.replaceAll(Config.getWwwpath(), "");
            fileName = fileName.replaceAll(Config.getWwwpath(), "");
            context.put("gotoPageHTML", BlogCommUtil.showStaticPageHtml(fileName, page, pages));
            addCommonContext(context);
            String path;
            int index = i + 1;
            if (index == 1) {
                path = filePath;
            } else {
                //path = filePath.split("\\.")[0]+index+"."+filePath.split("\\.")[1];
                String newFileName = fileName + index;//+fileName.split("\\.")[1];
                path = filePath.replace(fileName, newFileName);
            }

            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            template = VelocityFactory.getTemplate(templateName, "utf-8");
            mergeTemplate(template, context, file);
        }
        return true;

    }

    public static void addCommonContext(Context context) {
        context.put("dirService", BlogCoreServiceImpl.getInstance());
        context.put("cocService", BlogCoreServiceImpl.getInstance());
        context.put("currentUser", CurrentUser.getActiveUser());
        context.put("photoService", PhotoServiceImpl.getInstance());
        context.put("reviewService", BlogReviewServiceImpl.getInstance());
        context.put("messageService", BlogMessageServiceImpl.getInstance());
        context.put("userService", BlogUserServiceImpl.getInstance());
        context.put("linkService", FriendLinkServiceImpl.getInstance());
        context.put("resourceService",BlogResourceServiceImpl.getInstance());
        context.put("CommUtil", CommUtil.getInstance());
        context.put("HtmlUtil", HtmlUtil.getInstance());
        context.put("Config", Config.getInstance());
    }

    public String mergeFile(String mainFile, String contentFile, String[] navigatFile) {
        String main = file2String(mainFile);
        String content = file2String(contentFile);
        String navigate = file2String(navigatFile);
        main = main.replace("${content}", content);
        main = main.replace("${navigate}", navigate);
        return main;
    }

    public String file2String(String... filename) {
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        for (String str : filename) {
            try {
                reader = new BufferedReader(new FileReader(str));
                loadString(buffer, reader);
            } catch (FileNotFoundException e) {
                // TODO 自动生成 catch 块
                logger.error("file2String错误：" + e);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        // TODO 自动生成 catch 块
                        logger.error("file2String错误：" + e);
                    }
                }
            }
        }
        return buffer.toString();
    }

    protected void loadString(StringBuffer buffer, BufferedReader br) {
        String str;
        try {
            while ((str = br.readLine()) != null) {
                buffer.append(str).append("\n");
            }
        } catch (IOException e) {
            // TODO 自动生成 catch 块
            logger.error("loadString错误：" + e);
        }
    }

    protected static void mergeTemplate(Template template, Context context,
            File file) {
        Writer writer = null;
        VelocityWriter vw = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(file),template.getEncoding());
            vw = new VelocityWriter(writer, 4 * 1024, true);
            template.merge(context, vw);
            System.out.println("生成模板:"+file.getName());
        } catch (Exception e) {
            System.out.println("生成错误:"+file.getName()+",详见系统日志");
            logger.error("合成错误：" + e);
            //e.printStackTrace();
        } finally {
            if (vw != null) {
                try {
                    vw.flush();
                    vw.close();
                    writer.close();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    //e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        BlogInfo blog = BlogUserServiceImpl.getInstance().getBlogInfo("2120160614028616");
        HTMLGenerater.saveLeftReviewPhotoToHTML(blog);
        HTMLGenerater.saveLeftMusicToHTML(blog);
        HTMLGenerater.saveMusicConfigToXMl(blog);
        HTMLGenerater.saveMusicListToXMl(blog);
    }
}
